package uiao.step4_transaction_template;

import uiao.BankService;
import uiao.step3_connection_holder.ConnectionHolderBankDao;
import uiao.step3_connection_holder.ConnectionHolderInsuranceDao;

import javax.sql.DataSource;

public class TransactionTemplateBankService implements BankService {
    private DataSource dataSource;
    private ConnectionHolderBankDao connectionHolderBankDao;
    private ConnectionHolderInsuranceDao connectionHolderInsuranceDao;

    public TransactionTemplateBankService(DataSource dataSource) {
        this.dataSource = dataSource;
        connectionHolderBankDao = new ConnectionHolderBankDao(dataSource);
        connectionHolderInsuranceDao = new ConnectionHolderInsuranceDao(dataSource);
    }

    @Override
    public void transfer(final int fromId, final int toId, final int amount) {
        new TransactionTemplate(dataSource) {
            @Override
            protected void doJob() throws Exception {
                // 这个两个方法不能异步，需要和doJob方法一个线程执行
                connectionHolderInsuranceDao.deposit(toId, amount);
                connectionHolderBankDao.withdraw(fromId, amount);

            }
        }.doJobInTransaction();
    }
}
